const express = require('express');
const router = express.Router();
const staffsMapper = require('../mapper/staffsMapper');
const conn = require('../utils/conn');
const jwt = require('../utils/jwt');

router.post('/v1/staff', (req, res) => {
  const validate = jwt.validate(req, res);
  if(validate < 1) {
    return res;
  }

  const { userId, jName, city, salary, showResume } = req.body;
  if(userId != validate) {
    return res.send({ code: 418, err: "I'm a teapot" });
  }

  conn.query(staffsMapper.add, [ userId, jName, city, salary, showResume ], (err, data) => {
    if(err) {
      res.send({ code: 500, err });
    } if(data) {
      res.send({ code: 200, data });
    }
  });
});

router.put('/v1/staff', (req, res) => {
  const validate = jwt.validate(req, res);
  if(validate < 1) {
    return;
  }

  const { jName, city, salary, showResume, id } = req.body;
  conn.query(staffsMapper.update, [ jName, city, salary, showResume, id ], (err, data) => {
    if(err) {
      res.send({ code: 500, err });
    } if(data) {
      res.send({ code: 200, data });
    }
  });
});

router.get('/v1/staff', (req, res) => {
  const validate = jwt.validate(req, res);
  if(validate < 1) {
    return;
  }

  const { jName, city, userId, page, size } = req.query;
  const items = [ jName, jName, city, city, userId, (userId || typeof userId == 'number') ? Number(userId) : null, (page - 1) * size, Number(size) ];
  console.log(items);
  conn.query(staffsMapper.select, items, (err, data) => {
    if(err) {
      res.send({ code: 500, err });
    } if(data) {
      items.splice(items.length - 2, 2);
      conn.query(staffsMapper.count, items, (err, result) => {
        if(err) {
          res.send({ code: 500, err });
        } if(result && result.length) {
          res.send({ code: 200, data, count: result[0].total });
        }
      });
    }
  });
});

router.get('/v1/staff/:id', (req, res) => {
  const validate = jwt.validate(req, res);
  if(validate < 1) {
    return;
  }

  const id = req.params.id;
  conn.query(staffsMapper.detail, [ id ], (err, data) => {
    if(err) {
      res.send({ code: 500, err });
    } if(data) {
      console.log(data);
      res.send({ code: 200, data: data[0] });
    }
  });
});

router.delete('/v1/staff/:id', (req, res) => {
  const validate = jwt.validate(req, res);
  if(validate < 1) {
    return;
  }

  const id = req.params.id;
  conn.query(staffsMapper.delete, [ id ], (err, data) => {
    if(err) {
      res.send({ code: 500, err });
    } if(data) {
      res.send({ code: 200, data });
    }
  });
});

module.exports = router;